<?php

namespace App\Http\Controllers\My\Bid;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Auth;
use App\Model\Project;

class BidController extends Controller
{
    //
    protected $middleware = ['App\Http\middleware\Authenticate'=>[]];

    public function bid($pid){
    	$pro = DB::table('projects')->where('pid',$pid)->first();
    	return view('My.Bid.lijitouzi',['pro'=>$pro]);
    }

    public function touzi(Request $r,$pid){
        if($r->v_pstatus != 20){
            return '支付失败';
        }
        $key = '%()#QOKFDLS:1*&U';
        $md5str = strtoupper(md5($r->v_oid.$r->v_pstatus.$r->v_amount.$r->v_moneytype.$key));
        if($md5str !== $r->v_md5str){
            return '信息错误';
        }
    	$pro = Project::find($pid);
    	$row = array(
    		'uid'=>$r->user()->uid,
    		'pid'=>$pid,
    		'title'=>$pro->title,
    		'money'=>$r->money*100,
    		'pubtime'=>time()
    		);
    	$res = DB::table('bids')->insertGetId($row);
    	if(!$res){
    		return Redirect::back();
    	}else {
    		$pro->increment('received',$r->money*100);
    		if($pro->money == $pro->received){
    			$pro->status = 2;
    			$pro->save();
    			$this->touziDone($pro);
    		}
    		return '<script>alert("投资成功");location="/home";</script>';
    	}
    }

    public function touziDone($pro){
    	$row = array(
    		'uid'=>$pro->uid,
    		'pid'=>$pro->pid,
    		'title'=>$pro->title,
    		'amount'=>($pro->money*$pro->rate)/1200 + $pro->money/$pro->hrange,
    		'status'=>0 //未还款
    		);
        for( $i=1;$i<=$pro->hrange;$i+=1 ){
    		$row['paydate'] = date('Y/m/d',strtotime("+$i month"));
    		DB::table('hks')->insertGetId($row);
    	}

    	$bid = DB::table('bids')->where('pid',$pro->pid)->get();

    	$raw = array(
    		'pid'=>$pro->pid,
    		'title'=>$pro->title,
    		'enddate'=>date('Y/m/d',strtotime("+".$pro->hrange." month"))
    		);
    	foreach($bid as $v){
    		$raw['uid'] = $v->uid;
    		$raw['amount'] = $v->money*$pro->rate/36500;
    		DB::table('tasks')->insert($raw);
    	}
    }
}
